import axios from 'axios'
import { useUserStore } from '@/stores'

const baseURL = import.meta.env.VITE_BASE_URL

const instance = axios.create({
  baseURL,
  timeout: 120000,
})

const successfulMsgShowPath = new Set(
  ["/user/auth/login", "/user/merchant"]
)

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 携带token
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`
    }
    return config
  },
  (err) => Promise.reject(err),
)

// 响应拦截器
instance.interceptors.response.use(
  (res) => {
      ElMessage.success(res.data?.msg || '操作成功')
      // if (successfulMsgShowPath.has(res.config.url)) {
      //   ElMessage.success(res.data?.msg || '操作成功')
      // }

    return res
  },
  (err) => {
    switch (err.status) {
      case 401: {
        const userStore = useUserStore();
        userStore.removeToken();
        break;
      }
    }
    ElMessage.error(err.response?.data.msg || '网络异常！');
    return Promise.reject(err)
  },
)

export default instance
export { baseURL }
